<?php

namespace services\spoker;

use api\modules\mini\forms\spoker\SpokerForm;
use common\components\Service;
use common\helpers\CommonHelper;
use common\models\patient\Patient;
use common\models\spoker\Spoker;
use common\models\user\UserWithdrawAccount;
use services\log\LogMemberOpService;
use services\common\MessageService;
use services\user\UserWithdrawAccountService;
use Yii;
use yii\db\Exception;

class SpokerService extends Service
{
    /**
     * 获取登陆用户代言人信息
     * @return array
     */
    public function getUserInfo(): array
    {
        $user = Yii::$app->user->identity->user;
        $spoker = $user->spoker_id ? Spoker::findOne($user->spoker_id) : null;

        // 是否有切换正式测试权限
        $switch = false;
        if (in_array($user->mobile , Yii::$app->params['user_mobile_arr'])) {
            $switch = true;
        }

        return [
            'id' => $spoker->id ?? 0,
            'status' => $spoker->status ?? 0,
            'switch' => $switch,
        ];
    }

    /**
     * 新增代言人
     * @param SpokerForm $model
     * @return void
     * @throws \Exception
     */
    public static function create(SpokerForm $model): void
    {

        try {
            $transaction = Yii::$app->db->beginTransaction();

            // 1.创建代言人
            $spoker = new Spoker();
            $spoker->user_id = Yii::$app->user->identity->member_id;
            $spoker->name = $model->name;
            $spoker->mobile = $model->mobile;
            $spoker->referrer_name = $model->referrer_name ?: '';
            $spoker->status = Spoker::STATUS_WAIT;
            $spoker->saveAndCheckResult();

            // 2.更新用户表
            $user = $model->getUser();
            $user->spoker_id = $spoker->id;
            $user->saveAndCheckResult();

            $transaction->commit();
            // 3.推送审核消息
            MessageService::sendDingtalk(Yii::$app->params['dingtalk_code_spoker_add'], [
                'name' => $spoker->name,
                'referrer_name' => $spoker->referrer_name,
                'mobile' => $spoker->mobile,
            ]);
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /**
     * 代言人列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function spokerList(array $params, int $page, int $pageSize): array
    {
        $query = Spoker::find()
            ->alias('s')
            ->select([
                's.*',
                '(CASE s.status WHEN 0 THEN 3 WHEN 1 THEN 1 ELSE 2 END) status_new',
                'count(p.id) all_num',
                'sum(CASE WHEN p.data_status = '. Patient::DATA_STATUS_IN_HOSPITAL .' THEN 1 ELSE 0 END) in_hospital_num'
            ])
            ->leftJoin(Patient::tableName() . ' p', 's.id = p.spoker_id and p.status = ' . Patient::STATUS_ENABLE)
            ->groupBy('s.id');
        // 搜索代言人手机号、姓名
        if (isset($params['keywords']) && $params['keywords']) {
            if (is_numeric($params['keywords'])) {
                $query->andWhere(['like', 's.mobile', "{$params['keywords']}%", false]);
            } else {
                $query->andWhere(['like', 's.name', $params['keywords']]);
            }
        }
        // 状态
        if (isset($params['status']) && is_numeric($params['status'])) {
            $query->andWhere(['s.status' => $params['status']]);
        }
        $list = $this->getListPageRes($query, $page, $pageSize, ['status_new' => SORT_DESC, 's.id' => SORT_DESC]);
        foreach ($list['list'] as &$val) {
            $val['status_name'] = Spoker::$statuss[$val['status']] ?? '';
            $val['created_at_str'] = $val['created_at'] ? date('Y-m-d H:i', $val['created_at']) : '';
        }
        return $list;
    }

    /**
     * 状态下拉筛选项
     * @return array[]
     */
    public static function getStatusCondition(): array
    {
        return [
            ['value' => Spoker::STATUS_WAIT, 'label' => Spoker::$statuss[Spoker::STATUS_WAIT]],
            ['value' => Spoker::STATUS_SUCCESS, 'label' => Spoker::$statuss[Spoker::STATUS_SUCCESS]],
            ['value' => Spoker::STATUS_FAIL, 'label' => Spoker::$statuss[Spoker::STATUS_FAIL]],
        ];
    }

    /**
     * 代言人审核
     *
     * @param $params
     * @return array
     * @throws Exception
     */
    public function examine($params): array
    {
        $spokerIs = Spoker::findOne($params['id']);
        if (!$spokerIs || $spokerIs->status == Spoker::STATUS_SUCCESS) {
            return CommonHelper::api(422, '代言人已审核');
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            Spoker::updateAll([
                'status' => $params['status'],
                'audit_member_id' => Yii::$app->user->identity->member_id,
                'audit_time' => time(),
                'updated_at' => time(),
            ], ['id' => $params['id']]);

            // 添加日志
            LogMemberOpService::createSpokerLog('examine', Spoker::findOne($params['id']));
            $transaction->commit();
            return ['id' => $params['id']];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /**
     * 获取列表筛选项
     * @return array
     */
    public static function getListCondition(): array
    {
        return CommonHelper::getListCondition(self::getNormalListByIds(), ['value_column' => 'id', 'label_column' => 'name']);
    }

    /**
     * 根据Ids获取列表【审核通过的代言人】
     * @param array|null $ids
     * @param array $orId
     * @return array
     */
    public static function getNormalListByIds(?array $ids = null, array $orId = []): array
    {
        $query = Spoker::find()
            ->select(['*'])
            ->where([
                'status' => Spoker::STATUS_SUCCESS,
            ]);
        if (!is_null($ids)) {
            $query->andWhere(['id' => $ids]);
        }
        if ($orId) {
            $query->orWhere([
                'id' =>$orId,
                'status' => Spoker::STATUS_SUCCESS,
            ]);
        }
        return $query->orderBy(['id' => SORT_DESC])->all();
    }

    /**
     * 根据Ids获取列表【审核通过的代言人】
     * @param array|int $ids
     * @return Spoker[]
     */
    public static function getMapByIds(array|int $ids): array
    {
        $query = Spoker::find()
            ->where(['id' => $ids]);
        return $query->indexBy('id')->all();
    }

    /**
     * 获取代言人提现账号
     * @param int $id
     * @return Spoker[]
     */
    public function getSpokerAccount(int $id)
    {
        $spokerIs = Spoker::findOne($id);
        if (!$spokerIs) {
            return [];
        }
        $userWithdrawAccount = UserWithdrawAccount::findOne(['user_id' => $spokerIs->user_id]);
        return [
            'id' => $userWithdrawAccount->id ?? 0,
            'type' => $userWithdrawAccount->type ?? UserWithdrawAccount::TYPE_ALIPAY,
            'card_no' => $userWithdrawAccount->card_no ?? '',
            'name' => $userWithdrawAccount->name ?? '',
            'bank_name' => $userWithdrawAccount->bank_name ?? '',
            'condition' => [
                'type' => UserWithdrawAccountService::getConditionTypes()
            ],
        ];

    }
}